package com.sgtech.demo.controller;

import com.sgtech.demo.model.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.Session;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Base64;

/**
 * @Description:
 * @Author sgtech
 * @Date 2021/7/13 23:10
 **/
@Controller
@Slf4j
public class LoginController {
    @RequestMapping("/login")
    public String loginPage(){
        return "login";
    }

    @RequestMapping("/index")
    public String index(){
        return "index";
    }

    @PostMapping("/dologin")
    public String login(SysUser user,
                        HttpServletRequest request,
                        HttpServletResponse response,
                        Model model){
        // 判断用户名密码
        if(!("admin".equals(user.getUsername()) && "admin".equals(user.getPassword()))){
            return "redirect:login";
        }

        // 认证成功，向session中添加用户信息
        HttpSession session = request.getSession();
        session.setAttribute("user",user);

        // 判断是否勾选了记住我
        if(user.getRememberMe()!=null){
            // 为了演示方便token写死，为用户名：admin的base64编码
            Cookie cookie = new Cookie("boot_rememberMe", "YWRtaW4=");
            // 为了演示设置cookie过期时间为30s
            cookie.setMaxAge(30);
            response.addCookie(cookie);
        }

        return "redirect:index";
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        if (null == session || session.getAttribute("user") == null) {
            return "login";
        }
        session.invalidate();
        Cookie[] cookies = request.getCookies();
        if (ObjectUtils.isEmpty(cookies)) {

        } else {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (name.equals("boot_rememberMe")) {
                    cookie.setMaxAge(0);
                    response.addCookie(cookie);
                }
            }
        }

        return "login";

    }
}
